package com.xzzz.common.dblog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xzzz.common.base.pojo.PageRes;
import com.xzzz.common.dblog.mappers.LogMapper;
import com.xzzz.common.dblog.pojo.LevelCountRes;
import com.xzzz.common.dblog.pojo.LogEntity;
import com.xzzz.common.dblog.pojo.LogSearchReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Mybatis 保存数据到数据库
 */
@Slf4j
public class LogService {

    @Autowired
    private LogMapper logMapper;

    @Transactional(rollbackFor = Exception.class)
    public void save(List<LogEntity> logs) {
        if (logMapper == null) {
            return;
        }
        if (CollUtil.isEmpty(logs)) {
            return;
        }
        try {
            logMapper.save(logs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void expire() {
        long start = System.currentTimeMillis();
        Date today = DateUtil.date();
        Date expireDate = DateUtil.offsetDay(today, -1); // 删除1天前数据
        String expireDateStr = DateUtil.format(expireDate, "yyyy-MM-dd HH:mm:ss");
        int num = logMapper.delete(expireDateStr);
        log.info("[GUARDCAT] 删除小于 [{}] LOG  信息, 共:[{}], 用时: {}", expireDateStr, num, System.currentTimeMillis() - start);
    }

    /**
     * 搜索日志
     *
     * @param req
     * @return
     */
    public PageRes<LogEntity> search(LogSearchReq req) {
        Page<LogEntity> page = PageHelper.startPage(req.getPageNum(), req.getPageSize());
        PageRes<LogEntity> pageRes = new PageRes<>(logMapper.search(req));
        pageRes.setTotal(page.getTotal());
        pageRes.setPageNum(req.getPageNum());
        pageRes.setPageSize(req.getPageSize());
        return pageRes;
    }

    public List<LevelCountRes> countGroupByLevel(String appName) {
        DateTime endDate = DateUtil.date();
        DateTime beginDate = DateUtil.offsetDay(endDate, -1);
        String beginDT = DateUtil.format(beginDate, "yyyy-MM-dd HH:mm:ss");
        String endDT = DateUtil.format(endDate, "yyyy-MM-dd HH:mm:ss");
        return logMapper.countGroupByLevel(appName, beginDT, endDT);
    }

    /**
     * 查询24小时内的日志折线图
     *
     * @param appName 应用名称
     */
    public List<LevelCountRes> listGroupByLevel(String appName, Date startTime, Date entTime) {

        String beginDT = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
        String endDT = DateUtil.format(entTime, "yyyy-MM-dd HH:mm:ss");
        return logMapper.listGroupByLevel(appName, beginDT, endDT);
    }
}
